package com.lanzuo.collector.updater.utils;

import com.lanzuo.collector.updater.config.SpringContextHolder;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author eric
 * windows 服务相关工具类
 */
@Slf4j
@UtilityClass
public class WinServiceUtil {

    /**
     * 服务名称（注意：是服务的“服务名”，不是显示名）
     */
    private String serviceName = SpringContextHolder.getProperty("target.service_name");

    /**
     * 检查 Windows 服务是否正在运行
     *
     * @return true 表示服务正在运行，false 表示未运行或不存在
     */
    public static boolean isServiceRunning() {
        try {
            // 执行 sc query 命令
            Process process = Runtime.getRuntime().exec("sc query \"" + serviceName + "\"");
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "GBK")); // Windows 默认编码 GBK

            String line;
            while ((line = reader.readLine()) != null) {
                // 查找 STATE 行，例如：STATE              : 4  RUNNING
                if (line.contains("STATE")) {
                    // 检查是否包含 "RUNNING"
                    return line.contains("RUNNING");
                }
            }
            process.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * command 控制服务启停
     *
     * @param command stop/start
     */
    public void commandWinService(String command) {
        // 构造命令：sc stop 服务名
        ProcessBuilder pb = new ProcessBuilder("sc", command, serviceName);
        pb.redirectErrorStream(true); // 合并错误流

        try {
            Process process = pb.start();
            // 读取输出（兼容 Java 8）
            StringBuilder output = new StringBuilder();
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    output.append(line).append(System.lineSeparator());
                }
            }

            int exitCode = process.waitFor();
            if (exitCode == 0) {
                log.info("服务 [{}] {} 命令已发送。", serviceName, command);
            } else {
                log.info("停止服务失败，退出码: {}", exitCode);
                log.info("错误信息:\n {}", output.toString());
            }
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

}
